package com.epam.task.web.service.command;

import com.epam.task.web.entity.User;
import com.epam.task.web.entity.Users;
import com.epam.task.web.service.AbstractAction;
import com.epam.task.web.util.logging.LoggerUtil;
import org.apache.log4j.Logger;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class ShowUsers extends AbstractAction {

    LoggerUtil logger = new LoggerUtil(Logger.getLogger(ShowUsers.class.getClass()));

    @Override
    public String perform(HttpServletRequest request, HttpServletResponse response) {
        HttpSession session = request.getSession();
        ResultSet resultSet = find("oc_user", "user_group_id", String.valueOf(User.CUSTOMER));
        List<User> usersList = createUsersList(resultSet);

        session.setAttribute("oc_user", new Users(usersList));

        return "/managerViewCustomersList.jsp";
    }

    private List<User> createUsersList(ResultSet resultSet) {
        List<User> users = new ArrayList<>();

        try {
            while (resultSet.next()) {
                int id = (int) resultSet.getObject("user_id");
                users.add(createUserById(id));
            }

            return users;
        } catch (SQLException exception) {
            logger.getExceptionTextFileLogger().error(exception);
            return null;
        }
    }

}
